package org.wmq.travelagency02.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wmq.travelagency02.mapper.TourGroupMapper;
import org.wmq.travelagency02.model.Entity.TourGroup;
import org.wmq.travelagency02.model.Entity.TourGroupTraveller;
import org.wmq.travelagency02.service.SignUpService;
import org.wmq.travelagency02.service.TourGroupService;
import org.wmq.travelagency02.service.TourGroupTravellerService;

import java.math.BigDecimal;

@Service
@RequiredArgsConstructor
public class TourGroupServiceImpl extends ServiceImpl<TourGroupMapper, TourGroup> implements TourGroupService {
    @Autowired
    private TourGroupTravellerService tourGroupTravellerService;
    @Lazy
    @Autowired
    private SignUpService signUpService;

    @Override
    public TourGroup getById(Long id) {
        TourGroup result = this.lambdaQuery().eq(TourGroup::getId, id)
                .select(
                        TourGroup::getName,
                        TourGroup::getPrice,
                        TourGroup::getMaxSize,
                        TourGroup::getStatus,
                        TourGroup::getRouteId,
                        TourGroup::getGuidebookId,
                        TourGroup::getBeginTime,
                        TourGroup::getEndTime
                ).one();
        if (result == null){
            return null;
        }
        result.setId(id);
        return result;
    }

    @Override
    @Transactional
    public boolean removeById(Long id) {
        try {
            this.tourGroupTravellerService.lambdaUpdate()
                    .eq(TourGroupTraveller::getTourGroupId, id)
                    .remove();
        } catch (Exception e) {
            throw new RuntimeException("删除旅行团发生异常，删除旅行团游客信息时失败");

        }
        try {
            this.signUpService.removeByTourGroupId(id);
        } catch (Exception e) {
            throw new RuntimeException("删除旅行团时发生异常，删除报名表中旅行团信息失败");

        }
        return super.removeById(id);
    }

    @Override
    public BigDecimal getPriceById(Long id) {
        return this.lambdaQuery().eq(TourGroup::getId, id)
                .select(TourGroup::getPrice).one().getPrice();
    }
}
